const { Op } = require('sequelize');
const db = require('../models');
const redis = require('../config/redis');

const Record = db.Record;
const User = db.User;

/**
 * 排行榜控制器
 */
const leaderboardController = {
  /**
   * 获取全球排行榜
   * @param {Object} req 请求对象
   * @param {Object} res 响应对象
   * @param {Function} next 下一个中间件
   */
  async getGlobalLeaderboard(req, res, next) {
    try {
      const { level = 'easy', limit = 10, page = 1 } = req.query;
      
      // 尝试从Redis缓存获取
      const cacheKey = `leaderboard:${level}:${limit}:${page}`;
      const cachedData = await redis.get(cacheKey);
      
      if (cachedData) {
        return res.json({
          code: 0,
          message: '获取排行榜成功',
          data: JSON.parse(cachedData)
        });
      }
      
      // 计算分页
      const offset = (page - 1) * limit;
      
      // 查询排行榜数据
      const records = await Record.findAll({
        where: { level },
        attributes: ['id', 'userId', 'time', 'mistakes', 'hintsUsed', 'score', 'createdAt'],
        include: [
          {
            model: User,
            attributes: ['username', 'avatar']
          }
        ],
        order: [
          ['time', 'ASC'],  // 时间升序（越短越好）
          ['mistakes', 'ASC'],  // 错误次数升序（越少越好）
          ['hintsUsed', 'ASC'],  // 提示次数升序（越少越好）
          ['createdAt', 'DESC']  // 创建时间降序（越新越好）
        ],
        limit: parseInt(limit),
        offset: parseInt(offset)
      });
      
      // 转换数据格式
      const leaderboardData = records.map((record, index) => ({
        rank: offset + index + 1,
        id: record.id,
        username: record.User.username,
        avatar: record.User.avatar,
        time: record.time,
        mistakes: record.mistakes,
        hintsUsed: record.hintsUsed,
        score: record.score,
        date: record.createdAt
      }));
      
      // 缓存到Redis（1小时）
      await redis.set(cacheKey, JSON.stringify(leaderboardData), { EX: 3600 });
      
      res.json({
        code: 0,
        message: '获取排行榜成功',
        data: leaderboardData
      });
    } catch (error) {
      next(error);
    }
  },
  
  /**
   * 获取用户排名
   * @param {Object} req 请求对象
   * @param {Object} res 响应对象
   * @param {Function} next 下一个中间件
   */
  async getUserRank(req, res, next) {
    try {
      const userId = req.user.id;
      
      // 获取用户的最佳记录
      const user = await User.findByPk(userId, {
        attributes: ['id', 'username', 'avatar', 'bestRecords']
      });
      
      if (!user) {
        return res.status(404).json({
          code: 404,
          message: '用户不存在'
        });
      }
      
      const result = {};
      
      // 处理每个难度级别
      for (const level of ['easy', 'medium', 'hard']) {
        const bestTime = user.bestRecords?.[level];
        
        if (bestTime) {
          // 计算在此难度级别的排名
          const rank = await Record.count({
            where: {
              level,
              time: { [Op.lt]: bestTime }
            },
            distinct: true,
            col: 'userId'
          });
          
          result[level] = {
            rank: rank + 1,
            bestTime
          };
        } else {
          result[level] = null;
        }
      }
      
      res.json({
        code: 0,
        message: '获取用户排名成功',
        data: {
          userId: user.id,
          username: user.username,
          avatar: user.avatar,
          ...result
        }
      });
    } catch (error) {
      next(error);
    }
  },

  /**
   * 获取排行榜
   * @param {Object} req 请求对象
   * @param {Object} res 响应对象
   */
  getLeaderboard(req, res) {
    // 你的排行榜逻辑
    res.json({ success: true, leaderboard: [] });
  }
};

module.exports = leaderboardController;
